import { useRef, useState } from 'react';
import { ProCard, ProForm, ProFormList, ProFormText } from '@ant-design/pro-components';
import { Card, Button, Form, Table, Switch, InputNumber, Select, Radio } from 'antd';
import { PlusOutlined, MenuOutlined } from '@ant-design/icons';
import { arrayMoveImmutable } from 'array-move';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import type { SortEnd } from 'react-sortable-hoc';

import FindLinkModal from '../FindLinkModal';
import DragTable from './DragTable';
import styles from './index.less';

const initialData = [
  {
    id: Math.floor(Math.random() * (99999 - 10000 + 1)) + 10000,
    key: '0',
    index: 1,
    isDefault: false,
    isHidden: false,
    priceType: 'manual',
    price: 0,
    quantityLimit: 0,
  },
];

const mockStandardProducts = [
  { value: '1', label: '标准品A' },
  { value: '2', label: '标准品B' },
  { value: '3', label: '标准品C' },
];

// 自定义---拖拽手柄组件
const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);
// 拖拽子项
const SortableItem = SortableElement((props: React.HTMLAttributes<HTMLTableRowElement>) => (
  <div className={styles['sortable-item']}>
    <DragHandle />
    {props.children}
  </div>
));
// 拖拽容器
const SortableBody = SortableContainer((props: React.HTMLAttributes<HTMLTableSectionElement>) => (
  <>{props.children}</>
));

interface Propx {
  style?: any;
}

const CommboForm = (props: Propx) => {
  const { style = {} } = props;

  const actionRef = useRef<any>();

  const [formRef] = Form.useForm();

  const [dataSource, setDataSource] = useState(initialData);
  const [count, setCount] = useState(1);

  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [info, setInfo] = useState<any>(null);

  const handleOpenModal = () => {
    setModalVisible(true);
  };

  const handleModalCancel = () => {
    setModalVisible(false);
  };

  const handleModalSubmit = (data: any) => {
    console.log('Data submitted:', data);
    setModalVisible(false);
  };

  // 新增空白轮次
  const handleAddRound = () => {
    actionRef.current?.add({ name: '轮次', chajia: 'auto' });
    console.log('formRef', formRef.getFieldsValue());
  };

  // 新增固定轮次
  const handleAddFixedRound = () => {
    actionRef.current?.add({ name: '固定轮次', labels: [{ value: '333', label: '333' }] });
  };

  const handleDelete = (key: any) => {
    setDataSource(dataSource.filter((item) => item.key !== key));
  };

  const handleAdd = () => {
    const newData = {
      id: Math.floor(Math.random() * (99999 - 10000 + 1)) + 10000, // 随机数,
      key: count.toString(),
      index: count + 1,
      isDefault: false,
      isHidden: false,
      priceType: 'manual',
      price: 0,
      quantityLimit: 0,
    };
    setDataSource([...dataSource, newData]);
    setCount(count + 1);
  };

  const columns: any = (num: number) => [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      sorter: (a: any, b: any) => a.index - b.index,
    },
    {
      title: '标准品',
      dataIndex: 'standardProduct',
      key: 'standardProduct',
      render: (_: any, record: any) => (
        <Form.Item
          name={[`${num}`, 'list', `${record.key}`, 'standardProduct']}
          rules={[{ required: true, message: '必填' }]}
          noStyle
        >
          <Select
            style={{ width: '100%' }}
            placeholder="选择标准品"
            options={mockStandardProducts}
          />
        </Form.Item>
      ),
    },
    {
      title: '是否默认选中',
      dataIndex: 'isDefault',
      key: 'isDefault',
      render: (text: any, record: any) => (
        <Form.Item name={[`${num}`, 'list', `${record.key}`, 'isDefault']} noStyle>
          <Switch />
        </Form.Item>
      ),
    },
    {
      title: '是否隐藏',
      dataIndex: 'isHidden',
      key: 'isHidden',
      render: (text: any, record: any) => (
        <Form.Item name={[`${num}`, 'list', `${record.key}`, 'isHidden']} noStyle>
          <Switch />
        </Form.Item>
      ),
    },
    {
      title: () => {
        return (
          <Form.Item name={[`${num}`, 'chajia']} noStyle>
            <Radio.Group
              optionType="button"
              options={[
                { label: '手动差价', value: 'manual' },
                { label: '自动差价', value: 'auto' },
              ]}
            />
          </Form.Item>
        );
      },
      dataIndex: 'priceType',
      key: 'priceType',
      render: (text: any, record: any) => (
        <Form.Item name={[`${num}`, 'list', `${record.key}`, 'priceType']} noStyle>
          <InputNumber style={{ width: '100%' }} step={1} />
        </Form.Item>
      ),
    },
    {
      title: '数量上限',
      dataIndex: 'quantityLimit',
      key: 'quantityLimit',
      render: (text: any, record: any) => (
        <Form.Item name={[`${num}`, 'list', `${record.key}`, 'quantityLimit']} noStyle>
          <InputNumber style={{ width: '100%' }} step={1} />
        </Form.Item>
      ),
    },
    {
      title: '备键',
      dataIndex: 'remark',
      key: 'remark',
      render: () => (
        <Button type="link" onClick={() => handleOpenModal()}>
          查看
        </Button>
      ),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (text: any, record: any) => (
        <Button type="link" onClick={() => handleDelete(record.key)}>
          删除
        </Button>
      ),
    },
  ];

  // 拖拽动作结束
  const onSortEnd = ({ oldIndex, newIndex }: SortEnd) => {
    const { users } = formRef.getFieldsValue();
    if (oldIndex !== newIndex && users) {
      const newData = arrayMoveImmutable(users.slice(), oldIndex, newIndex).filter(
        (el: any) => !!el,
      );
      formRef.setFieldsValue({
        users: newData,
      });
    }
  };

  return (
    <div className={styles.formBox} style={{ height: 300, ...style }}>
      <Card type="inner" title="套餐组成结构化" className={styles.cardBox}>
        <ProForm
          onFinish={async (e) => console.log(e)}
          form={formRef}
          submitter={{
            render: false, // 隐藏默认的提交按钮
          }}
        >
          <div className={styles.btnBox}>
            <Button icon={<PlusOutlined />} onClick={handleAddRound}>
              新增空白轮次
            </Button>
            <Button icon={<PlusOutlined />} onClick={handleAddFixedRound}>
              新增固定轮次
            </Button>
          </div>
          <SortableBody
            useDragHandle // 自定义可拖拽区域
            disableAutoscroll // 禁止拖拽时滑动效果
            onSortEnd={onSortEnd}
            axis="y"
          >
            <ProFormList
              name="users"
              actionRef={actionRef}
              initialValue={[]}
              copyIconProps={false}
              creatorButtonProps={false}
              itemRender={({ listDom, action }, { record, index }) => {
                return (
                  <SortableItem index={index}>
                    <ProCard
                      bordered
                      extra={action}
                      title={`${record?.name}${index + 1}`}
                      style={{
                        marginBlockEnd: 8,
                      }}
                    >
                      <ProFormText width={'lg'} name="roundName" label="轮次名称" />
                      {/* 列表 */}
                      {/* <Table
                        dataSource={dataSource}
                        columns={columns(index)}
                        rowKey="id"
                        pagination={false}
                      /> */}
                      <DragTable
                        dataSource={dataSource}
                        setDataSource={setDataSource}
                        mockStandardProducts={mockStandardProducts}
                      />
                      <Button
                        type="dashed"
                        onClick={handleAdd}
                        style={{
                          width: '240px',
                          marginTop: '20px',
                          marginBottom: '20px',
                          display: 'block',
                        }}
                        icon={<PlusOutlined />}
                      >
                        添加
                      </Button>
                    </ProCard>
                  </SortableItem>
                );
              }}
            ></ProFormList>
          </SortableBody>
        </ProForm>
      </Card>
      <FindLinkModal
        open={modalVisible}
        info={info}
        onSubmit={handleModalSubmit}
        onCancel={handleModalCancel}
      />
    </div>
  );
};

export default CommboForm;
